import { getCode, registerFn, LoginFn, getUserInfo, outlogin } from "@/api/register";

const state = {
  code: '',
  token: localStorage.getItem('shopToken') || '',
  info: JSON.parse(localStorage.getItem('info')) || {}
}

const mutations = {
  // 获取用户信息
  getUserInfoFn(state, info) {
    state.info = info
    localStorage.setItem('info', JSON.stringify(info))
  },
  // 注册
  LoginFn(state, token) {
    state.token = token
  },
  // 获取验证码
  getCode(state, code) {
    state.code = code
  },
  // 退出登录
  outLoginFn(state) {
    // 把仓库中相关用户信息清空
    state.token = ''
    state.info = {}
    // 把本地存储清空
    localStorage.removeItem('shopToken')
    localStorage.removeItem('info')
  }
}

const actions = {
  // 退出登录
  async outLoginFn({commit}) {
    let res = await outlogin()
    console.log(res);
    if (res.data.code === 200) {
      // actions不能直接修改state的值，需要通知mutations
      commit('outLoginFn')
      return 'ok'
    } else {
      return Promise.reject(new Error(res.data.message))
    }
  },
  // 获取用户信息
  async getUserinfoFn({commit}) {
    let res = await getUserInfo()
    console.log(res)
    if (res.data.code === 200) {
      commit('getUserInfoFn', res.data.data)
    }
  },
  // 发起登录请求
  async LoginFn({commit}, data) {
    let res = await LoginFn(data)
    // console.log(res)
    if (res.data.code === 200) {
      localStorage.setItem('shopToken', res.data.data.token)
      commit('LoginFn', res.data.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error(res.data.message))
    }
  },
  // 发起注册请求
  async registerFn({commit}, data) {
    let res = await registerFn(data)
    // console.log(res);
    if (res.data.code === 200) {
      console.log(commit)
      return '注册成功'
    } else {
      return Promise.reject(new Error(res.data.message))
    }
  },
  // 获取验证码
  async getCode({commit}, phone) {
    let res = await getCode(phone)
    // console.log(res);
    if (res.data.code === 200) {
      commit('getCode', res.data.data)
    } else {
      return res.data.message
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}